package com.future.bantang.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.future.bantang.R;
import com.future.bantang.adapter.ShoppingListFragmentPagerAdapter;
import com.future.bantang.app.BanTangAPP;
import com.future.bantang.constants.BanTang;
import com.future.bantang.entity.ShoppingListEntity;
import com.future.bantang.eventmas.BaseEventMsg;
import com.future.bantang.utils.JsonUtils;
import com.future.bantang.utils.L;
import com.future.bantang.utils.NetUtils;
import com.future.bantang.view.PagerSlidingTabStrip;
import com.future.bantang.view.ScrollMonitorableScrollView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ContentView;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import cn.sharesdk.onekeyshare.OnekeyShare;
import de.greenrobot.event.EventBus;

@ContentView(R.layout.activity_shopping_list)
public class ShoppingListActivity extends BaseActivity {
    @ViewInject(R.id.layout_activity_shopping_list_header)
    private RelativeLayout mLayoutHeader;
    @ViewInject(R.id.layout_activity_shopping_list_content)
    private LinearLayout mLayoutContent;
    @ViewInject(R.id.iv_activity_shopping_list_summury)
    private ImageView mIvSummuryPic;
    @ViewInject(R.id.tv_activity_shopping_list_title)
    private TextView mTvSummuryTitle;
    @ViewInject(R.id.tv_activity_shopping_list_desc)
    private TextView mTvSummuryDesc;
    @ViewInject(R.id.sv_activity_shopping_list)
    private ScrollMonitorableScrollView mScrollView;
    @ViewInject(R.id.tv_activity_shopping_list_title)
    private TextView mTvHeaderTitle;
    @ViewInject(R.id.layout_activity_shopping_list_title)
    private FrameLayout mLayoutTilte;
    @ViewInject(R.id.vp_activity_shopping_list_content)
    private ViewPager mVpContent;
    @ViewInject(R.id.psts_activity_shopping_list_content)
    private PagerSlidingTabStrip mPSTabStrip;
    @ViewInject(R.id.layout_shopping_list_summury)
    private LinearLayout mLayoutSummury;

    private ShoppingListFragmentPagerAdapter mSLFragentPagerAdapter;

    @Override
    protected void init() {
        super.init();

        Intent intent=getIntent();
        id=intent.getStringExtra("id");

        measureHeaderHeight();
        setScrollViewListener();

        mSLFragentPagerAdapter=new ShoppingListFragmentPagerAdapter(getSupportFragmentManager());
        mVpContent.setAdapter(mSLFragentPagerAdapter);


        WindowManager windowManager= (WindowManager) getSystemService(WINDOW_SERVICE);
        DisplayMetrics outmetrics=new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(outmetrics);
        float density=outmetrics.density;

        mPSTabStrip.setViewPager(mVpContent);
        mPSTabStrip.setIndicatorColorResource(R.color.pink);
        mPSTabStrip.setIndicatorHeight(5);
        mPSTabStrip.setTextSize((int) (15 * density));
        mPSTabStrip.setSelectedTextColorResource(R.color.pink);
        mPSTabStrip.setShouldExpand(true);
        mPSTabStrip.setTextColorResource(R.color.light_gray);

        //测试方法，后续需删除
        testMethod();
    }








    private float lastY=0;
    private boolean isFirst=true;
    /**
     * 设置ScrollView的监听，监听相关子view的位置，设置头部的透明度
     */
    private void setScrollViewListener() {
        mScrollView.setOnTouchListener(new View.OnTouchListener() {

            Handler monitorHandler=new Handler(){
                @Override
                public void handleMessage(Message msg) {
                    super.handleMessage(msg);
                    View v= (View) msg.obj;
                    float y=v.getScrollY();
                    L.d("lastY=" +lastY+ ",mTvSummuryTitle.getScrollY()=" + y);

                    if (y!=lastY) {
                        lastY=y;
                        setHeaderAlpha(lastY);
                        setParentIntercept(lastY);
                        monitorHandler.sendMessageDelayed(monitorHandler.obtainMessage(0, v), 5);
                        isFirst=false;
                    }else {
                        if (isFirst){
                            monitorHandler.sendMessageDelayed(monitorHandler.obtainMessage(0, v), 15);
                            isFirst=true;
                        }
                    }

                }
            };

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        lastY=v.getScrollY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        lastY=v.getScrollY();
                        setHeaderAlpha(lastY);
                        setParentIntercept(lastY);
                        L.d("touch="+",mTvSummuryTitle.getScrollY()="+lastY);
                        break;
                    case MotionEvent.ACTION_UP:
                        monitorHandler.sendMessageDelayed(monitorHandler.obtainMessage(0,v),5);
                        break;
                }

                return false;
            }
        });
    }


    /**
     * 设置父控件是否拦截事件
     * @param scrollY
     */
    private void setParentIntercept(float scrollY){
        if(scrollY>=(layoutSummuryHeight-statusBarHeight-headerHeight)){
            mScrollView.setIsIntercapt(false);
        }else {
            mScrollView.setIsIntercapt(true);
        }
    }



    private float alpha=0;
    /**
     * 设置顶部导航背景的透明度
     * @param scrollY
     */
    private void setHeaderAlpha(float scrollY){
        float alphaPart=0;
        if(scrollY<0){
            if (alpha>0){
                L.d("alpha=0");
                alpha=0;
                mLayoutTilte.setAlpha(alpha);
            }
        }else if (scrollY>ivSummuryPicHeight){
            if (alpha<1){
                L.d("alpha=1");
                alpha=1;
                mLayoutTilte.setAlpha(alpha);
            }
        }else {
            alphaPart=scrollY;
            alpha=alphaPart/ivSummuryPicHeight;
            mLayoutTilte.setAlpha(alpha);
            L.d("alpha="+alpha);
        }
    }

    private void testMethod() {
        int childCount = mScrollView.getChildCount();
        L.d("childCount=" + childCount);
        mScrollView.getChildAt(1);



    }

    //获取到的状态栏的高度
    private int statusBarHeight=0;
    //summury图片的高度
    private int ivSummuryPicHeight;
    //summury部分高度
    private int layoutSummuryHeight=0;
    //头部导航栏高度
    private int headerHeight;
    private boolean isMeasure=false;
    private void measureHeaderHeight() {
        ViewTreeObserver mLayoutHeaderObserver=mLayoutHeader.getViewTreeObserver();
        mLayoutHeaderObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasure) {
                    headerHeight = mLayoutHeader.getMeasuredHeight();
                    int ResId = getResources().getIdentifier("status_bar_height", "dimen", "android");
                    statusBarHeight = getResources().getDimensionPixelSize(ResId);
                    WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
                    DisplayMetrics outMetrics = new DisplayMetrics();
                    windowManager.getDefaultDisplay().getMetrics(outMetrics);
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            outMetrics.heightPixels - statusBarHeight - headerHeight);
                    mLayoutContent.setLayoutParams(params);
                    ivSummuryPicHeight = mIvSummuryPic.getMeasuredHeight();
                    layoutSummuryHeight=mLayoutSummury.getMeasuredHeight();
                    L.d("layoutSummuryHeight="+layoutSummuryHeight);
                    isMeasure=true;
                }
                return true;
            }
        });
    }



    public class ShoppingListMsg extends BaseEventMsg<ShoppingListEntity>{
        private ScrollMonitorableScrollView mScrollView;

        public ScrollMonitorableScrollView getmScrollView() {
            return mScrollView;
        }

        public void setmScrollView(ScrollMonitorableScrollView mScrollView) {
            this.mScrollView = mScrollView;
        }
    }


    public class UserRecommendMsg extends BaseEventMsg<String>{
        private ScrollMonitorableScrollView mScrollView;

        public ScrollMonitorableScrollView getmScrollView() {
            return mScrollView;
        }

        public void setmScrollView(ScrollMonitorableScrollView mScrollView) {
            this.mScrollView = mScrollView;
        }
    }



    private int pageIndex=0;
    private int pageSize=10;
    //需从上一级传递进来
    private String id=null;

    private ShoppingListEntity shoppingListEntity;

    @Override
    protected void loadDatas() {
        super.loadDatas();
        RequestParams requestParams = new NetUtils.RequestParamsBuilder()
                .addPostParameter(BanTang.CLIENT_ID_KEY, BanTang.CLIENT_ID_VALUE)
                .addPostParameter(BanTang.CLIENT_SECRET_KEY, BanTang.CLIENT_SECRET_VALUE)
                .addPostParameter(BanTang.PAGE, pageIndex + "")
                .addPostParameter(BanTang.PAGESIZE, pageSize + "")
                .addPostParameter(BanTang.ID, id)
                .build();
        NetUtils.loadShoppingListDatas(requestParams, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                L.d("network success");
                try {
                    shoppingListEntity = JsonUtils.perse(responseInfo.result, ShoppingListEntity.class);
                    ShoppingListEntity.DataEntity data = shoppingListEntity.getData();
                    BanTangAPP.getApp().getImageLoader().displayImage(data.getPic(), mIvSummuryPic);
                    mTvSummuryTitle.setText(data.getTitle());
                    mTvSummuryDesc.setText(data.getDesc());

                    //将shoppingListEntity传递给精选Fragment
                    ShoppingListMsg msg=new ShoppingListMsg();
                    msg.setStr(id);
                    msg.setT(shoppingListEntity);
                    msg.setmScrollView(mScrollView);
                    EventBus.getDefault().post(msg);

                    UserRecommendMsg userRecommendMsg=new UserRecommendMsg();
                    userRecommendMsg.setStr(id);
                    userRecommendMsg.setT(shoppingListEntity.getData().getTag_ids());
                    userRecommendMsg.setmScrollView(mScrollView);
                    EventBus.getDefault().post(userRecommendMsg);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.e("network failed",error.getMessage());
            }
        });
    }


    @OnClick({R.id.iv_activity_shopping_list_back,R.id.iv_activity_shopping_list_share})
    private void backToHomeFragment(View view){
        switch (view.getId()){
            case R.id.iv_activity_shopping_list_back:
                finish();
                break;
            case R.id.iv_activity_shopping_list_share:
                share();
                break;
        }

    }

    private void share() {
        OnekeyShare oneKeyShare = BanTangAPP.getApp().getOneKeyShare();

        oneKeyShare.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oneKeyShare.setTitle(shoppingListEntity.getData().getTitle());
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oneKeyShare.setTitleUrl(shoppingListEntity.getData().getShare_url());
        // text是分享文本，所有平台都需要这个字段
        oneKeyShare.setText(shoppingListEntity.getData().getDesc());
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oneKeyShare.setImageUrl(shoppingListEntity.getData().getShare_pic());
        // url仅在微信（包括好友和朋友圈）中使用
        oneKeyShare.setUrl(shoppingListEntity.getData().getShare_url());
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oneKeyShare.setComment("说点什么...");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oneKeyShare.setSite("半糖精选");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oneKeyShare.setSiteUrl(shoppingListEntity.getData().getShare_url());

// 启动分享GUI
        oneKeyShare.show(this);
    }


}
